package com.omp.common.util;

import org.apache.commons.lang.xwork.StringUtils;
import org.springside.modules.orm.Page;

public class SqlUtil {

	/**
	 * 通过page对象的orderBy、order属性生成order by语句，多个字段、排序方向用“,”（英文半角逗号分隔）。
	 * @author jianghao
	 * @param page 分页对象
	 * @return String order by语句
	 */
	public static <T> StringBuffer buildOrderBy(Page<T> page) {
		StringBuffer hql = new StringBuffer("");
		if (null!=page && StringUtils.isNotBlank(page.getOrderBy())) {
			if (page.getOrderBy().indexOf(",") != -1) { //多字段排序
				String[] orderBy = page.getOrderBy().split(",");
				if (StringUtils.isBlank(page.getOrder())) { //指定了排序方向
					hql.append(" order by ").append(page.getOrderBy());
				} else if (page.getOrder().indexOf(",") == -1) { //指定了单个排序方向
					hql.append(" order by ");
					for (String str : orderBy) {
						hql.append(str).append(" ").append(page.getOrder()).append(",");
					}
					hql.deleteCharAt(hql.length() - 1);
				} else { //指定了多个排序方向
					String[] order = page.getOrder().split(",");
					if (order.length == orderBy.length) { //排序字段与排序方向长度可对应
						hql.append(" order by ");
						for (int i = 0;i < orderBy.length;i++) {
							hql.append(orderBy[i]).append(" ").append(order[i]).append(",");
						}
						hql.deleteCharAt(hql.length() - 1);
					} else { //排序字段与排序方向长度不可对应
						//不指定排序方向
						hql.append(" order by ").append(page.getOrderBy());
					}
				}
			} else { //单字段排序
				hql.append(" order by ").append(page.getOrderBy());
				if (StringUtils.isNotBlank(page.getOrder())) {
					hql.append(" ").append(page.getOrder().indexOf(",") > 0 ? page.getOrder().split(",")[0] : page.getOrder().indexOf(","));
				}
			}
		}
		return hql;
	}
}
